<template>
  <div v-if="room" style="height: 88vh">
    <el-drawer
      :title="room.name"
      :visible.sync="drawer"
      :before-close="handlerClose"
      :show-close="true"
      :wrapperClosable="false"
      size="100vw"
    >
      <div class="room-detail">
        <div class="desc">
          <div class="flex">
            <img
              style="transform: rotateY(180deg)"
              src="@img/chair_empty.svg"
            />
            <span> 可预约</span>
          </div>
          <div class="flex">
            <img
              style="transform: rotateY(180deg)"
              src="@img/chair_picked.svg"
            />
            <span> 已被预约</span>
          </div>
        </div>

        <seats :seats="seats" @select="select" @msg="msg" :open="room.open" />
        <div class="info">
          <div>开放时间:</div>
          <div>
            <el-tag
              v-for="(day, index) of JSON.parse(room.open_time)"
              :key="index"
              style="margin-left: 6px"
              >{{ day }}</el-tag
            >
          </div>
        </div>
        <div class="info">
          <div>地点:</div>
          <div>{{ room.located }}</div>
        </div>
        <div class="info">
          <div>是否可预约:</div>
          <div>{{ room.open ? "可预约" : "不可预约" }}</div>
        </div>
        <div class="info">
          <div>剩余座位数:</div>
          <div>{{ remainingSeats }}</div>
        </div>
        <div v-if="room.open && !hasAppointment">
          <div class="info">
            <div>在座时间:</div>
            <time-picker
              @updateState="updateState"
              :open_time="JSON.parse(room.open_time)"
            />
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import Seats from "@components/content/Seats";
import { getOneReadingRoom } from "@network/manager";
import { getAppointmentNum, appointmentInDateTime } from "@network/student";
import TimePicker from "@components/content/TimePicker";
import {
  hasAppointment,
  makeAppointment,
  getSeatState,
} from "@network/student";

export default {
  components: { Seats, TimePicker },
  props: {
    id: {
      type: Number,
      default() {
        0;
      },
    },
  },
  data() {
    return {
      room: null,
      drawer: true,
      hasAppointment: false,
      appointment: null,
      seats: null,
      seatsBackUp: null,
      changed: false,
      selected: 0,
      timer: {
        date: "",
        startTime: "",
        endTime: "",
      },
      appointmentNum: -1,
      hasOtherAppointmentInDate: false,
    };
  },
  computed: {
    remainingSeats() {
      return this.room.total - this.selected;
    },
  },
  methods: {
    //获取值类型
    verifyType(target) {
      return Object.prototype.toString.call(target).slice(8, -1);
    },
    //是否为引用类型
    isReferenceType(target) {
      let ReferenceTypes = ["Object", "Array", "Set", "Map"];
      return ReferenceTypes.includes(this.verifyType(target));
    },
    //深拷贝
    deepCopy(target) {
      let obj = {};

      for (let attr in target) {
        if (this.isReferenceType(target[attr])) {
          obj[attr] = this.deepCopy(target[attr]);
        } else {
          obj[attr] = target[attr];
        }
      }

      return obj;
    },
    updateState(timer) {
      this.timer = timer;
      this.getSeatState();
    },
    shrinkEndTime(time1) {
      if (time1.slice(-2) == "00") {
        let time = parseInt(time1.slice(0, 2)) - 1;
        time1 = (time < 10 ? "0" + time : time) + ":59";
      } else if (time1.slice(-2) == "30") {
        time1 = time1.replace("30", "29");
      }
      return time1;
    },
    enlargeStartTime(time1) {
      time1 = time1.replace("00", "01");
      time1 = time1.replace("30", "31");
      return time1;
    },
    async getSeatState() {
      if (this.timer.date && this.timer.endTime && this.timer.startTime) {
        let room_id = this.id,
          date = new Date(this.timer.date)
            .toLocaleDateString()
            .replace(/\//g, "-"),
          start_time = date + " " + this.enlargeStartTime(this.timer.startTime),
          end_time = date + " " + this.shrinkEndTime(this.timer.endTime);
        console.log("appointmentInDateTime", start_time, end_time, date);
        getSeatState({
          room_id,
          start_time,
          end_time,
        }).then(async (res) => {
          if (res.data.tag) {
            let selected = res.data.data;

            selected.forEach((v) => {
              this.$set(this.seats[v.type][v.row][v.col], v.idx, 1);
              this.changed = true;
              this.selected = selected.length;
            });
          } else {
            if (this.changed) {
              this.selected = 0;
              this.changed = false;
              this.$set(this, "seats", this.deepCopy(this.seatsBackUp));
            }
          }
          this.$forceUpdate();
          await appointmentInDateTime({
            start_time,
            end_time,
            date,
          }).then(async (res) => {
            if (res.data.tag) {
              this.$message.error("该时间段您已有预约,请查看您的预约");
              this.hasOtherAppointmentInDate = true;
            } else {
              this.hasOtherAppointmentInDate = false;
            }
          });
        });
      }
    },

    async select(info) {
      if (!this.room.open) return;
      if (this.hasAppointment) {
        this.$message.info("该阅览室您已有预约座位");
        return;
      }
      if (this.hasOtherAppointmentInDate) {
        this.$message.error("该时间段您已有预约,请查看您的预约");
        return;
      }
      if (!this.timer.date || !this.timer.startTime || !this.timer.endTime) {
        this.$message.info("请先选择时间");
      } else if (this.appointmentNum >= 3) {
        this.$message.warning("您已有三个预约,不可再预约更多");
      } else {
        let date = new Date(this.timer.date)
            .toLocaleDateString()
            .replace(/\//g, "-"),
          start_time = date + " " + this.timer.startTime,
          end_time = date + " " + this.timer.endTime,
          room_id = this.room.id,
          { type, row, col, idx } = info;
        this.seats[info.type][info.row][info.col][info.idx] = 1;
        this.$confirm("确定预约该座位?", "预约确认", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          closeOnClickModal: false,
          type: "info",
        })
          .then(() => {
            makeAppointment({
              start_time,
              end_time,
              room_id,
              type,
              row,
              col,
              idx,
              date,
            }).then((res) => {
              if (res.data.tag) {
                this.load();
                this.$message.success("预约成功");
              } else {
                this.$message.error("预约失败");
              }
            });
          })
          .catch(() => {
            this.$message.warning("已取消");
          });
      }
    },
    handlerClose() {
      this.drawer = false;
      this.$emit("done");
    },
    load() {
      getOneReadingRoom(this.id).then((res) => {
        if (res.data.tag) {
          this.room = res.data.room[0];
          this.$set(this, "seats", JSON.parse(this.room.seats));
          this.seatsBackUp = JSON.parse(this.room.seats);
        }
      });
      hasAppointment({ room_id: this.id }).then((res) => {
        this.hasAppointment = res.data.tag;
      });
      getAppointmentNum().then((res) => {
        this.appointmentNum = res.data.data[0].num;
        console.log("get_appointment_num", res);
      });
    },
    msg() {
      if (this.room.open) {
        this.$message.info("该位置已被预约");
      }
    },
  },

  created() {
    this.load();
  },

  mounted() {},
};
</script>
<style scoped>
.room-detail {
  flex-direction: column;
  padding: 20px;
}

.ruleForm {
  margin-left: -20px;
}

.btn {
  display: flex;
  justify-content: right;
  gap: 10px;
  padding: 10px;
}

.submit {
  position: absolute;
  display: flex;
  gap: 10px;
  bottom: 30px;
  right: calc(50% - 245px);
}

.submit > button {
  min-width: 120px;
  width: 240px;
  margin: 0 auto;
}

.info {
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid rgb(194, 194, 194);
  padding: 10px;
  flex-wrap: wrap;
  width: 100%;
  box-sizing: border-box;
}

.info > div:nth-child(1) {
  color: cornflowerblue;
}

.desc {
  display: flex;
  align-items: center;
  gap: 10px;
}

@media screen and (max-width: 480px) {
  >>> .el-drawer {
    height: 100vh;
    overflow: auto;
  }
}
</style>
